// miniprogram/pages/shop_cart/shop_cart.js
const db = wx.cloud.database()
const shopcartCollection = db.collection("shopcart") 
const _ = db.command
var allprice = 0
var shopcart = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopcart,
    selectAllStatus:false,
    checked:false
    // totalPrice
  },
  deleteShop(e){
    // console.log(e);
    let index = e.currentTarget.dataset.id;
    console.log(index);
    shopcart.splice(index,1);
    console.log(shopcart);
    this.setData({
      shopcart:shopcart
    })
    shopcartCollection.add({
      shopcart
    })
  },
  selectshop(e){
    let index = e.currentTarget.dataset.index
    const selected = shopcart[index].selected;
    shopcart[index].selected = !selected
    this.setData({
      shopcart:shopcart
    })
    this.getTotalPrice();
  },
  getTotalPrice(){
    let total = 0;
    for(let i =0;i<shopcart.length;i++){
      if(shopcart[i].selected){
        total +=shopcart[i].C_Number *shopcart[i].C_price;
      }
    }
    this.setData({
      shopcart:shopcart,
      totalPrice:total.toFixed(2)
    })
  },
  selectAll(){
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    for(let i=0;i<shopcart.length;i++){
      shopcart[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus:selectAllStatus,
      shopcart:shopcart
    });
    this.getTotalPrice();
  },
  onChange(e){
    let number = e.detail;
    let index = e.currentTarget.dataset.index
    console.log(number,index);
    shopcart[index].C_Number = number
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let {data} = await shopcartCollection.get()
    this.setData({
      shopcart:data,
      totalPrice:0
    })
    shopcart = data
    console.log(shopcart);  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow () {
    let {data} = await shopcartCollection.get()
    this.setData({
      shopcart:data,
      totalPrice:0
    })
    shopcart = data
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    setTimeout(()=>{
      wx.stopPullDownRefresh()
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})